#include "main.h"
// 要求将所有代码写在本文件内

int ListInitiate(SLNode **head)/*初始化*/ {
    *head = (SLNode*) malloc(sizeof(SLNode));
    (*head)->next = NULL;
    if ((*head)->next != NULL)
        return 1;
    else
        return 0;
}

int ListLength(SLNode *head) /* 单链表的长度*/{
    SLNode *p = head; // 指针类型SLNode 设变量要带*
    int j = 0;
    while (p->next != NULL){
        p = p->next;
        j++;
    }
    return j;
}

int ListInsert(SLNode *head, int i, DataType x) {
    SLNode *p, *s;
    p = head;
    int j = -1;
    while (p->next != NULL && j < i-1){
        p = p->next;
        j++;
    }
    if (j != i-1) {
        return 1;
    }
    s = (SLNode*) malloc(sizeof (SLNode));
    s->data = x;
    s->next = p->next;
    p->next = s;
    return 0;
}

int ListDelete(SLNode *head, int i, DataType *x) {
    SLNode *p = head, *s;
    int j = -1;
    while (p->next != NULL && j < i-1){
        p = p->next;
        j++;
    }
    if ( j != i-1) {
        return 0;
    }
    s = p->next;
    p->next = p->next->next;
    *x = s->data;
    free(s);
    return 1;
}

int ListGet(SLNode *head, int i, DataType *x) {
    SLNode  *p = head;
    int j = -1;
    while (p->next != NULL && j < i) {
        p = p->next;
        j++;
    }
    if(i != j)
        return 0;
    else
        *x = p->data;
    return 1;
}

int Destroy(SLNode **head){
    SLNode *p, *q;
    p = *head;
    while (p != NULL){
        q = p;
        p = p->next;
        free(q);
    }
    (*head) = NULL;
    return 0;
}

void main(void) {
    SLNode *head;
    int i , x;
    ListInitiate(&head);/*初始化*/
    for(i = 0; i < 10; i++) {
        if(ListInsert(head, i, i+1) == 1) /*插入10个数据元素*/
        {
            printf("false1 \n");
            return;
        }
    }

    if(ListDelete(head, 4, &x) == 0) { /*删除数据元素5*/
        printf("false2 \n");
        return;
    }
    printf("%d\n", ListLength(head));

    for(i = 0; i < ListLength(head); i++) {
        if(ListGet(head, i, &x) == 0) /*取元素*/
        {
            printf("false3 \n");
            return;
        }
        else printf("%d    ", x);/*显示数据元素*/
    }

    Destroy(&head);
}
